package com.liuzhilong.infrastructure.basic.decorator.chain;


import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 控制链
 */
public class MessageHandlerChain {
    private static final transient List<MessageHandler> HOLDER = new ArrayList<>();
    private static List<MessageHandler> getSortedList(){
        return HOLDER.stream().sorted(Comparator.comparing(MessageHandler::getOrder)).collect(Collectors.toList());
    }
    public static final void append(MessageHandler messageHandler){
        HOLDER.add(messageHandler);
    }

    private  List<MessageHandler> handlers;
    private Iterator<MessageHandler> iterator;
    public void exec(Message message){
        if(iterator.hasNext()){
            iterator.next().exec(message,this);
        }

    }

    private MessageHandlerChain(){
        handlers =getSortedList();
        iterator = handlers.iterator();
    }
    public static MessageHandlerChain create(){
        return new MessageHandlerChain();
    }

}
